import { defineStore } from 'pinia'
import { loginApi, paymentApi, gzhYesApi, allnumApi } from '@/api/app'
import { setToken, getToken, setItem, getItem } from '@/utils/storage'
import { fetchMyInfo } from '@/api/my'

export const appStore = defineStore('app', {
  unistorage: true, // 是否持久化到内存
  state: () => {
    return {
      gzhStatus: false // 是否关注公众号
    }
  },
  actions: {
    // 初始化App状态
    initAppStatus () {
      setItem('initPromptStatus', true) // 注册返回温馨提示，每次进入小程序只显示一次
      setItem('initSurnameStatus', true) // 完善称呼温馨提示，每次进入小程序只显示一次
      setItem('initSkillStatus', true) // 脱单技巧弹窗，每次进入小程序只显示一次
      setItem('initNoticeStatus', true) // 关注公众号弹窗，每次进入小程序只显示一次
    },

    // 获取公众号订阅状态
    getGzhStatus () {
      return new Promise((resolve, reject) => {
        gzhYesApi()
          .then(res => {
            this.gzhStatus = res.msg == '已开启'
            resolve(this.gzhStatus)
          })
          .catch(err => {
            resolve(false)
          })
      })
    },

    // 注册接口
    sureRegister (user_info) {
      return new Promise((resolve, reject) => {
        uni.login({
          provider: 'weixin', //使用微信登录
          onlyAuthorize: true,
          success: async function (res) {
            try {
              // 调用开发者后台 登录接口
              const params = {
                code: res.code
              }
              params.user_info = user_info || ''
              const { data } = await loginApi(params)
              if (data?.token) {
                setToken(data.token)
                resolve()
              } else {
                reject()
              }
            } catch (error) {
              reject(error)
            }
          },
          fail: function (err) {
            reject(err)
          }
        })
      })
    },

    // 获取个人信息
    getUserInfo () {
      return new Promise(async (resolve, reject) => {
        try {
          const token = getToken()
          if (!token) {
            reject()
            return
          }
          const { data } = await fetchMyInfo()

          if (data) {
            data?.forEach(v => {
              if (v.userInfo?.year) {
                const y = v.userInfo?.year
                v.userInfo.full_year = y
                v.userInfo.year = String(y).slice(-2)
              }
              v.userInfo.count = v.count
              v.userInfo.member = v.member
              v.userInfo.imgs = v.noimg.slice(0, 3)

              v.userInfo.appLogin = baseStatus(v.userInfo)
              v.userInfo.isComplete = isComplete(v.userInfo)
              v.userInfo.isFullAddress = isFullAddress(v.userInfo)
              if (v.num) {
                const arr = Object.values(v.num)
                v.userInfo.nums = arr.filter(v => Number(v.day_look) > 0)
              }
            })
            setItem('user_info', data[0]?.userInfo)
            resolve(data[0]?.userInfo)
          } else {
            reject()
          }
        } catch (error) {
          reject(error)
        }
      })
    },

    // 支付
    surePayment (params) {
      return new Promise(async (resolve, reject) => {
        try {
          paymentApi(params)
            .then(res => {
              const { payment } = res.data
              uni.requestPayment({
                signType: 'MD5',
                provider: 'payment',
                package: payment.prepay_id,
                ...payment,
                success: function (res) {
                  setItem('confirmPay', true)
                  resolve()
                },
                fail: function (err) {
                  let msg = '支付失败，请稍候再试'
                  if (err.errMsg.includes('cancel')) {
                    msg = '取消支付'
                  }
                  uni.showToast({
                    title: msg,
                    icon: 'none'
                  })
                  reject(err)
                },
                complete: function (res) {}
              })
            })
            .catch(err => {})
        } catch (error) {
          reject(error)
        }
      })
    },

    // 获取查看次数
    fetchAllnum () {
      return new Promise((resolve, reject) => {
        allnumApi()
          .then(res => {
            const count = res.data[0]
            resolve(count)
          })
          .then(err => {
            reject(err)
          })
      })
    }
  }
})

// 查询当前用户是否已完成基础六步资料注册
const baseStatus = (data = {}) => {
  let isBase = true
  const { gender, year, height, edu, income, at_province, at_city } = data
  const bases = [gender, year, height, edu, income, at_province, at_city] || []
  bases.forEach(v => {
    if (!v) {
      isBase = false
    }
  })

  return isBase
}

// 未完善资料 - 底部提示弹窗（第一屏出现，页面上滑消失）
const isComplete = (data = {}) => {
  let com = true
  const {
    surname,
    relation,
    old_city,
    occupation,
    house,
    car,
    marriage,
    day_marr,
    mate_height,
    mate_age,
    mate_edu
  } = data
  const keys =
    [
      surname,
      relation,
      old_city,
      occupation,
      house,
      car,
      marriage,
      day_marr,
      mate_height,
      mate_age,
      mate_edu
    ] || []
  keys.forEach(v => {
    if (!v) {
      com = false
    }
  })

  return com
}

const isFullAddress = data => {
  let flag = true

  const { mate_address } = data

  if (mate_address) {
    const list = JSON.parse(mate_address)
    if (list?.length && list?.length < 3) {
      flag = false
    }
  } else {
    flag = false
  }

  return flag
}
